package cn.bytecollege.filter;

import cn.bytecollege.constant.Resource;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 过滤器，过滤登录、添加和修改管理员信息时，出现不合法数据返回原页面并给出提醒
 * @author qy
 */
@WebFilter(filterName = "AdminDateRuleFilter",servletNames = {"AdminLoginController","AdminAddController","AdminUpdateController"})
public class AdminDateRuleFilter implements Filter {
    String msg = null;
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //转型获取请求的类型和地址
        HttpServletRequest req = (HttpServletRequest) request;
        String uri = req.getRequestURI();
        String method = req.getMethod();
        //获取请求数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //根据正则表达式定出用户名和密码规则
        Pattern usernamePattern = Pattern.compile("\\w{5,12}");
        //判断是否为post提交表单
        if (method.equalsIgnoreCase("post")){
            Matcher usernameMatcher = usernamePattern.matcher(username);
            if(!usernameMatcher.matches()){
                msg = "用户名只能包含数字、字母、下划线，长度为5-12位";
                request.setAttribute("msg",msg);
                forward(request,response,uri);
                return;
            }

            Matcher passwordMatcher = usernamePattern.matcher(password);
            if(!passwordMatcher.matches()){
                msg = "密码只能包含数字、字母、下划线，长度为5-12位";
                request.setAttribute("msg",msg);
                forward(request,response,uri);
                return;
            }
        }
        chain.doFilter(request,response);
    }

    /**
     * 判断请求类型，跳转到相应页面
     * @param request
     * @param response
     * @param uri
     * @throws ServletException
     * @throws IOException
     */
    public void forward(ServletRequest request, ServletResponse response,String uri) throws ServletException, IOException {
        if (uri.equals("/admin/login")){
            request.setAttribute("msg",msg);
            request.getRequestDispatcher(Resource.PAGE_LOCATION+"login.jsp").forward(request, response);
        }else if (uri.equals("/adminAdd")){
            request.setAttribute("msg",msg);
            request.getRequestDispatcher(Resource.PAGE_LOCATION+"adminAdd.jsp").forward(request, response);
        }else if (uri.equals("/admin/updateAdmin")){
            request.setAttribute("msg",msg);
            request.getRequestDispatcher(Resource.PAGE_LOCATION+"adminUpdate.jsp").forward(request, response);
        }
    }
}
